<template>
  <div class="m-2">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" v-if="aAccessData?.update" @click="fnOpenAddRole"
          >新增角色</a-button
        >
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button
            style="padding: 0 6px"
            type="link"
            @click="handleEdit({ ...record, isLook: true })"
            >查看</a-button
          >
          <a-button
            style="padding: 0 6px"
            type="link"
            @click="handleEdit(record)"
            v-if="aAccessData?.update"
            >编辑</a-button
          >
          <a-button
            style="padding: 0 6px"
            v-if="record.status === 0 && aAccessData?.del"
            type="link"
            danger
            @click="handleDelete(record)"
            >删除</a-button
          >
        </template>
      </template>
    </BasicTable>
    <RoleDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';

  import { BasicTable, useTable } from '@/components/Table';
  import { useDrawer } from '@/components/Drawer';

  import RoleDrawer from './RoleDrawer.vue';
  import { columns, searchFormSchema } from './role.data';

  import { getAuthRoleList, delAuthRoleItem } from '@/api/system/account';
  import { fnApiGetAccessMenu } from '@/utils/auth';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createConfirm, createMessage } = useMessage();

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    title: '角色列表',
    api: getAuthRoleList,
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    resizeHeightOffset: 20,
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });
  const aAccessData: any = ref({});

  onMounted(async () => {
    aAccessData.value = await fnApiGetAccessMenu();
  });

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'warning',
      title: '提示',
      content: `确认要删除当前角色吗?`,
      onOk: async () => {
        await delAuthRoleItem({ id: record.id }, { AccessId: 8 });
        createMessage.success('删除角色成功');
        handleSuccess();
      },
    });
  }

  function handleSuccess() {
    reload();
  }

  function fnOpenAddRole() {
    openDrawer(true, {
      isUpdate: false,
    });
  }
</script>
